package com.rp.system.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.rp.common.utils.JsonUtil;
import com.rp.controller.RpController;
import com.rp.system.po.Organ;
import com.rp.system.service.OrganService;

/**
 * 组织结构管理
 * @author 黄健
 *
 */
@Controller
@RequestMapping("/rp/system/organMng/")
public class OrganController extends RpController {

	@Autowired
	private OrganService organService;
	
	@RequestMapping("showOrganGrid")
	public ModelAndView showOrganGrid(){
		model.put(WEBPAGE_TITLE, "部门管理");
		return forward("/rp/system/organMng/organGrid.jsp");
	}
	
	@ResponseBody
	@RequestMapping("getOrgans")
	public List<Organ> getOrgans(String name){
		
		return organService.getOrganDao().getOrgans(name);
	}
	
	@ResponseBody
	@RequestMapping("saveOrgans")
	public String saveOrgans(String json){
		List<Organ> organs;
		try {
			organs = JsonUtil.jsonToList(json, "com.rp.system.po.Organ");
			for (Organ organ : organs) {
				if(organ.getId() == null){
					organService.addOrgan(organ);
				}else{
					organService.updateOrgan(organ);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_MSG+e.getMessage();
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("deleteOrgans")
	public String deleteOrgans(String json){
		List<Organ> organs;
		try {
			organs = JsonUtil.jsonToList(json, "com.rp.system.po.Organ");
			for (Organ organ : organs) {
				organService.deleteOrgan(organ.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_MSG+e.getMessage();
		}
		
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("moveOrgansToRoot")
	public String moveOrgansToRoot(String[] ids){
		organService.moveOrgansToRoot(ids);
		return SUCCESS;
	}
	
	@ResponseBody
	@RequestMapping("moveOrgans")
	public String moveOrgans(String[] ids, String targetId){
		try {
			organService.moveOrgans(ids, targetId);
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return SUCCESS;
	}
	
}
